import json
import sqlite3
import time
from threading import Thread

import flask
from flask import request

import TgAuto
import TgJJAuto

server = flask.Flask(__name__)

dbName = 'shareTg.db'


@server.route('/status')
def index2():
    return "success"


@server.route('/')
def index1():
    return "success."


@server.route('/delete', methods=['post'])
def deleteLink():
    link = request.form['link']
    link = str(link).strip()
    print('接收数据link:', link)
    res = {'msg': '分享的链接不能为空', 'code': 2}
    if len(link.strip()) == 0:
        return json.dumps(res)
    delete(link)
    res = {'msg': 'success', 'code': 1}
    return json.dumps(res)


@server.route('/shareTg', methods=['post'])
def shareCs():
    return index(2)


@server.route('/shareTgJJ', methods=['post'])
def shareJJ():
    return index(3)


# success：-1默认；0正在分享；1分享完成；2代表等待分享的cs链接；3代表等待分享的jj链接
def index(type):
    link = request.form['link']
    link = str(link).strip()
    print('接收数据link:', link)
    res = {'msg': '分享的链接不能为空', 'code': 2}
    if len(link.strip()) == 0:
        return json.dumps(res)
    status = select(link)
    res = {'msg': '分享的链接已经存在', 'code': 3}
    if status != -1:
        return json.dumps(res)
    res = {'msg': '有分享的链接正在执行，此分享链接已加入分享队列', 'code': 4}
    if selectStatus(0) != -1:
        insert(link, type)
        return json.dumps(res)
    res = {'msg': 'success', 'code': 1}
    t = Thread(target=task, args=('子线程', link, type))
    t.start()
    return json.dumps(res)


def task(name, link, type):
    insert(link, 0)
    shareCsLink(link, name, type)
    time.sleep(2)
    print('%s is done' % name)


def shareCsLink(link, name, type):
    print('%s is runing ' % name)
    if type == 2:
        print('执行CS分享')
        TgAuto.share(link)
    else:
        TgJJAuto.share(link)
        print('执行JJ分享')

    time.sleep(5)
    print('___执行完毕：', type)
    update(link, 1)
    # 执行完毕后判断分享过程中是否有新的分享链接进入队列，如果有则继续把队列里的链接分享出去
    mLink = selectLink(2)
    print('mLinkCs==', mLink)
    if mLink:
        print('执行队列分享')
        update(mLink, 0)
        shareCsLink(mLink, name, 2)
    mLink = selectLink(3)
    print('mLinkJJ==', mLink)
    if mLink:
        print('执行队列分享')
        update(mLink, 0)
        shareCsLink(mLink, name, 3)


def createDb():
    conn = sqlite3.connect(dbName)
    c = conn.cursor()
    c.execute(
        '''
        CREATE TABLE SHARE
           (
           ID INTEGER  PRIMARY KEY      ,
           TIME            TEXT     ,
           LINK           TEXT     NOT NULL,
           SUCCESS         INT,
           TIME_STR            TEXT     
           );
           '''
    )
    conn.commit()
    conn.close()


def insert(url, success):
    conn = sqlite3.connect(dbName)
    c = conn.cursor()
    mTime = time.localtime()
    time1 = time.strftime("%Y-%m-%d %H:%M:%S", mTime)
    c.execute("INSERT INTO SHARE (TIME,TIME_STR,LINK,SUCCESS) \
          VALUES ('{}','{}','{}','{}')".format(time.time(), time1, url, success))
    conn.commit()
    conn.close()


def selectStatus(success):
    conn = sqlite3.connect(dbName)
    c = conn.cursor()
    status = -1

    # cursor = c.execute("SELECT id, TIME,LINK,CONTENT,link  from DAILY")
    # select * from 'log_info' order by id desc limit 1
    cursor = c.execute("SELECT  *  FROM SHARE  WHERE SUCCESS = ?", (success,))
    for row in cursor:
        status = row[3]
        print("ID = ", row[0], "TIME = ", row[1], "LINK = ", row[2], "SUCCESS = ", row[3], "TIME_STR = ", row[4], "\n")
    conn.close()
    return status


# 查询等待分享的链接
def selectLink(success):
    conn = sqlite3.connect(dbName)
    c = conn.cursor()
    link = None

    # cursor = c.execute("SELECT id, TIME,LINK,CONTENT,link  from DAILY")
    # select * from 'log_info' order by id desc limit 1
    cursor = c.execute("SELECT  *  FROM SHARE  WHERE SUCCESS = ?", (success,))
    for row in cursor:
        link = row[2]
        print("ID = ", row[0], "TIME = ", row[1], "LINK = ", row[2], "SUCCESS = ", row[3], "TIME_STR = ", row[4], "\n")
    conn.close()
    return link


def select(title):
    conn = sqlite3.connect(dbName)
    c = conn.cursor()
    success = -1

    # cursor = c.execute("SELECT id, TIME,LINK,CONTENT,link  from DAILY")
    # select * from 'log_info' order by id desc limit 1
    cursor = c.execute("SELECT  *  FROM SHARE  WHERE LINK = ?", (title,))
    for row in cursor:
        success = row[3]
        print("ID = ", row[0], "TIME = ", row[1], "LINK = ", row[2], "SUCCESS = ", row[3], "TIME_STR = ", row[4], "\n")
    conn.close()
    return success


def update(title, success):
    conn = sqlite3.connect(dbName)
    c = conn.cursor()

    c.execute("UPDATE SHARE set SUCCESS = " + str(success) + " where LINK = ?", (title,))
    conn.commit()
    print("Total number of rows updated :", conn.total_changes)
    conn.close()


def delete(title):
    conn = sqlite3.connect(dbName)
    c = conn.cursor()

    c.execute("DELETE from SHARE where LINK=?", (title,))
    conn.commit()
    print("Total number of rows deleted :", conn.total_changes)

    cursor = conn.execute("SELECT id,LINK,SUCCESS from SHARE")
    for row in cursor:
        print("ID = ", row[0], "LINK = ", row[1], "SUCCESS = ", row[2], "\n")
    conn.close()


if __name__ == '__main__':
    server.run('0.0.0.0',port='8003', debug=True)
    # server.run(port='8003', debug=True)
    # createDb()
    # insert('test', 0)
